﻿using CommonHelper;
using CommonModel.IDS4Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace IDS4API.Controllers
{
    /// <summary>
    /// 用户登录相关接口
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IConfiguration _configuration;
        private readonly IDatabase _redis;

        public LoginController(ILogger<LoginController> logger, IConfiguration configuration, RedisHelper client)
        {
            _logger = logger;
            _configuration = configuration;
            _redis = client.GetDatabase();
        }

        /// <summary>
        /// 用户登录接口
        /// </summary>
        /// <param name="param">用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginParam param)
        {
            try
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict["client_id"] = "testclient";
                dict["client_secret"] = "testsecret";
                dict["grant_type"] = "password";
                dict["username"] = param.UserName;
                dict["password"] = param.Password;

                using (HttpClient http = new HttpClient())
                using (var content = new FormUrlEncodedContent(dict))
                {
                    var msg = await http.PostAsync($"http://localhost:{Request.HttpContext.Connection.LocalPort}/connect/token", content);
                    if (!msg.IsSuccessStatusCode)
                    {
                        return BadRequest("登陆失败！");
                    }
                    string loginResult = await msg.Content.ReadAsStringAsync();
                    //将请求结果存储在redis里，供请求时验证权限使用
                    _redis.StringSet(param.UserName, loginResult, TimeSpan.FromHours(2));

                    return Ok(loginResult);
                }
            }
            catch (Exception ex)
            {
                return BadRequest("登陆失败！");
            }
        }
    }
}
